package com.itheima.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.stock.mapper.SysPermissionMapper;
import com.itheima.stock.pojo.entity.SysUser;
import com.itheima.stock.service.ISysUserService;
import com.itheima.stock.vo.resp.LoginUser;
import org.checkerframework.checker.units.qual.A;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 主要用于用户信息查询
 * 并将用户信息封装到UserDetails中
 * 由springSecurity框架验证密码
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private ISysUserService userService;
    @Resource
    private SysPermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名查询用户信息
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username);
        SysUser user = userService.getOne(wrapper);


        //用户不存在
        if (Objects.isNull(user)){
            throw new RuntimeException("用户不存在") ;
        }

        //用户按钮权限查询
        List<String> perms =  permissionMapper.selectMenuPermsByUserId(user.getId());


        //用户数据封装
        return new LoginUser(user, perms);
    }
}
